<!-- build time:Tue Dec 17 2019 19:26:48 GMT+0800 (GMT+08:00) --><!doctype html><html class="theme-next mist" lang="zh-Hans"><head><meta name="generator" content="Hexo 3.8.0"><meta name="google-site-verification" content="7Tau9WyVgxnsEY9oYedu9g0U6_8akOX3wiKbaYcrg9A"><meta name="baidu-site-verification" content="EVwLiaxdxX"><link href="/css/xps13.css" rel="stylesheet" type="text/css"><link href="/css/message.css" rel="stylesheet" type="text/css"><script type="text/javascript" src="/js/jquery-1.11.3.min.js"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css"><link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css"><meta name="keywords" content="MongoDB,DataBase,"><link rel="alternate" href="/atom.xml" title="MrBird" type="application/atom+xml"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1"><meta name="description" content="MongoDB查询涵盖以下几个方面：1.使用find或者findOne函数和查询文档对数据库执行查询；2.使用$条件查询实现范围查询，数据集包含查询，不等式查询，以及其它一些查询；3.查询将会返回一个数据库游标，游标只会在你需要时才将需要的文档批量返回；4.针对游标执行的元操作，包括忽略一定数量的结果，或者限定返回结果的数量，以及对结果排序。"><meta name="keywords" content="MongoDB,DataBase"><meta property="og:type" content="article"><meta property="og:title" content="MongoDB 文档查询"><meta property="og:url" content="http://mrbird.cc/MongoDB-文档查询.html"><meta property="og:site_name" content="MrBird"><meta property="og:description" content="MongoDB查询涵盖以下几个方面：1.使用find或者findOne函数和查询文档对数据库执行查询；2.使用$条件查询实现范围查询，数据集包含查询，不等式查询，以及其它一些查询；3.查询将会返回一个数据库游标，游标只会在你需要时才将需要的文档批量返回；4.针对游标执行的元操作，包括忽略一定数量的结果，或者限定返回结果的数量，以及对结果排序。"><meta property="og:locale" content="zh-Hans"><meta property="og:updated_time" content="2019-10-28T12:14:46.250Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="MongoDB 文档查询"><meta name="twitter:description" content="MongoDB查询涵盖以下几个方面：1.使用find或者findOne函数和查询文档对数据库执行查询；2.使用$条件查询实现范围查询，数据集包含查询，不等式查询，以及其它一些查询；3.查询将会返回一个数据库游标，游标只会在你需要时才将需要的文档批量返回；4.针对游标执行的元操作，包括忽略一定数量的结果，或者限定返回结果的数量，以及对结果排序。"><script type="text/javascript" id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Mist",sidebar:{position:"left",display:"always",offset:12,offset_float:0,b2t:!1,scrollpercent:!1},fancybox:!1,motion:!1}</script><title>MongoDB 文档查询 | MrBird</title></head><body ondragstart="return!1" class="animsition" lang="zh-Hans" style="overflow-x:hidden;padding-right:280px"><script type="text/javascript" src="/js/mo.min.js"></script><style>@media (min-width:768px) and (max-width:991px){body .header-innerr{width:700px!important}}.header-innerr{margin:0 auto;padding:100px 0 70px;width:880px}@media (min-width:1600px){.container .header-innerr{width:1200px}}.header-innerr{position:relative}.header-innerr{padding:20px 0 0}.header-innerr:after,.header-innerr:before{content:" ";display:table}.header-innerr:after{clear:both}@media (max-width:767px){.header-innerr{width:auto;padding:10px;margin-bottom:-20px}}</style><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><link href="https://fonts.font.im/css?family=Merienda" rel="stylesheet"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title" style="font-family:Merienda;font-size:1.3rem">MrBird</span> <span class="logo-line-after"><i></i></span></a></div><p class="site-subtitle"></p></div><div class="site-nav-toggle"><button><span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section">HOME</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">ARCHIVES</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section">TAGS</a></li><li class="menu-item menu-item-friends"><a href="/friends/" rel="section">FRIENDS</a></li><div class="sidebar-toggle" style="display:none"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div></ul><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i> </span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"><input autocomplete="off" placeholder="Search" spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div><div class="header-innerr"><div class="note info" style="margin:0;letter-spacing:.15px">🐤手把手教你搭建<strong>Spring Cloud微服务权限系统</strong>（从零到部署）：<a style="color:#40dab2;font-weight:600" href="https://www.kancloud.cn/mrbird/spring-cloud" target="_blank">https://www.kancloud.cn/mrbird/spring-cloud</a></div></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><link itemprop="mainEntityOfPage" href="http://mrbird.cc/MongoDB-文档查询.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="MrBird"><meta itemprop="description" content=""><meta itemprop="image" content="/images/blogImage.jpg"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="MrBird"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">MongoDB 文档查询</h1><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><span class="post-meta-item-text">Posted on</span> <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-02-22T14:17:26+08:00">2017-02-22 </time></span><span></span> <span class="post-meta-divider">|</span> <span class="page-pv"><i class="fa fa-laptop"></i>&nbsp;&nbsp;Visit count <span class="busuanzi-value" id="busuanzi_value_page_pv"></span></span></div></header><div class="post-body" itemprop="articleBody"><p>MongoDB查询涵盖以下几个方面：</p><p>1.使用find或者findOne函数和查询文档对数据库执行查询；</p><p>2.使用$条件查询实现范围查询，数据集包含查询，不等式查询，以及其它一些查询；</p><p>3.查询将会返回一个数据库游标，游标只会在你需要时才将需要的文档批量返回；</p><p>4.针对游标执行的元操作，包括忽略一定数量的结果，或者限定返回结果的数量，以及对结果排序。<a id="more"></a></p><h2 id="find简介"><a href="#find简介" class="headerlink" title="find简介"></a>find简介</h2><p>指定需要返回的键</p><p>比如，我只对blog集合的博文post感兴趣，可以使用以下查询语句：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.blog.find(&#123;&#125;,&#123;<span class="string">"post"</span>:1&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58acf0743c8ad0b0d9d65f45"</span>), <span class="string">"post"</span> : <span class="string">"MongoDB文档CUD"</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58acf64b3c8ad0b0d9d65f4a"</span>), <span class="string">"post"</span> : <span class="string">"MongoDB shell"</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58acf65d3c8ad0b0d9d65f4d"</span>), <span class="string">"post"</span> : <span class="string">"start Spring Boot"</span> &#125;</span><br></pre></td></tr></table></figure><p></p><p>如果不希望返回“_id”，可以这样：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.blog.find(&#123;&#125;,&#123;<span class="string">"post"</span>:1,<span class="string">"_id"</span>:0&#125;)</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"MongoDB文档CUD"</span> &#125;</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"MongoDB shell"</span> &#125;</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"start Spring Boot"</span> &#125;</span><br></pre></td></tr></table></figure><p></p><h2 id="查询条件"><a href="#查询条件" class="headerlink" title="查询条件"></a>查询条件</h2><h3 id="比较操作符"><a href="#比较操作符" class="headerlink" title="比较操作符"></a>比较操作符</h3><p>MongoDB中的比较操作符有五种，其中<code>$gt</code>，<code>$gte</code>，<code>$lt</code>，<code>$lte</code>分别对应<code>&gt;</code>，<code>&gt;=</code>，<code>&lt;</code>，<code>&lt;=</code>，比如查询blog阅读量pageview大于5的文档：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.blog.find(&#123;<span class="string">"pageview"</span>:&#123;<span class="string">"<span class="variable">$gte</span>"</span>:5&#125;&#125;).pretty()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"_id"</span> : ObjectId(<span class="string">"58acf0743c8ad0b0d9d65f45"</span>),</span><br><span class="line">    <span class="string">"name"</span> : <span class="string">"mrbird's blog"</span>,</span><br><span class="line">    <span class="string">"post"</span> : <span class="string">"MongoDB文档CUD"</span>,</span><br><span class="line">    <span class="string">"pageview"</span> : 5,</span><br><span class="line">    <span class="string">"like"</span> : 2,</span><br><span class="line">    <span class="string">"date"</span> : ISODate(<span class="string">"2017-02-22T05:45:03.006Z"</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>这四种操作符也可用于日期比较，比如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&gt; var date = new Date(<span class="string">"01/01/2017"</span>)</span><br><span class="line">&gt; db.blog.find(&#123;<span class="string">"date"</span>:&#123;<span class="string">"<span class="variable">$gte</span>"</span>:date&#125;&#125;,</span><br><span class="line">... &#123;<span class="string">"post"</span>:1,<span class="string">"date"</span>:1,<span class="string">"_id"</span>:0&#125;)</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"MongoDB文档CUD"</span>, <span class="string">"date"</span> : ISODate(<span class="string">"2017-02-22T05:45:03.006Z"</span>) &#125;</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"MongoDB shell"</span>, <span class="string">"date"</span> : ISODate(<span class="string">"2017-02-22T05:45:03.006Z"</span>) &#125;</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"start Spring Boot"</span>, <span class="string">"date"</span> : ISODate(<span class="string">"2017-02-22T05:45:03.006Z"</span>) &#125;</span><br></pre></td></tr></table></figure><p></p><p>另外一个比较操作符为<code>$ne</code>，<code>not equal</code>，可以用于所有类型，比如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.blog.find(&#123;<span class="string">"post"</span>:&#123;<span class="string">"<span class="variable">$ne</span>"</span>:<span class="string">"MongoDB shell"</span>&#125;&#125;,</span><br><span class="line">... &#123;<span class="string">"post"</span>:1&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58acf0743c8ad0b0d9d65f45"</span>), <span class="string">"post"</span> : <span class="string">"MongoDB文档CUD"</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58acf65d3c8ad0b0d9d65f4d"</span>), <span class="string">"post"</span> : <span class="string">"start Spring Boot"</span> &#125;</span><br></pre></td></tr></table></figure><p></p><h3 id="OR查询"><a href="#OR查询" class="headerlink" title="OR查询"></a>OR查询</h3><p><code>$in</code>操作符可以查询一个键的多个值，比如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.blog.find(&#123;<span class="string">"post"</span>:&#123;<span class="string">"<span class="variable">$in</span>"</span>:[<span class="string">"MongoDB文档CUD"</span>,<span class="string">"MongoDB shell"</span>]&#125;&#125;,</span><br><span class="line">... &#123;<span class="string">"post"</span>:1,<span class="string">"_id"</span>:0&#125;)</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"MongoDB文档CUD"</span> &#125;</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"MongoDB shell"</span> &#125;</span><br></pre></td></tr></table></figure><p></p><p>其中数组中的值可以是不同类型的。</p><p>与<code>$in</code>相反的是<code>$nin</code>，如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.blog.find(&#123;<span class="string">"post"</span>:&#123;<span class="string">"<span class="variable">$nin</span>"</span>:[<span class="string">"MongoDB文档CUD"</span>,<span class="string">"MongoDB shell"</span>]&#125;&#125;,</span><br><span class="line">... &#123;<span class="string">"post"</span>:1,<span class="string">"_id"</span>:0&#125;)</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"start Spring Boot"</span> &#125;</span><br></pre></td></tr></table></figure><p></p><p><code>$or</code>操作符和SQL中的含义类似，比如查询post为MongoDB文档CUD或者pageview为3的文档：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.blog.find(&#123;<span class="string">"<span class="variable">$or</span>"</span>:[&#123;<span class="string">"post"</span>:<span class="string">"MongoDB文档CUD"</span>&#125;,&#123;<span class="string">"pageview"</span>:3&#125;]&#125;,</span><br><span class="line">...&#123;<span class="string">"post"</span>:1,<span class="string">"pageview"</span>:1,<span class="string">"_id"</span>:0&#125;).pretty()</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"MongoDB文档CUD"</span>, <span class="string">"pageview"</span> : 5 &#125;</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"MongoDB shell"</span>, <span class="string">"pageview"</span> : 3 &#125;</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"start Spring Boot"</span>, <span class="string">"pageview"</span> : 3 &#125;</span><br></pre></td></tr></table></figure><p></p><h3 id="not"><a href="#not" class="headerlink" title="$not"></a>$not</h3><p><code>$mod</code>为取模运算符，比如查询pageview为3的倍数的博文：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.blog.find(&#123;<span class="string">"pageview"</span>:&#123;<span class="string">"<span class="variable">$mod</span>"</span>:[3,0]&#125;&#125;,&#123;<span class="string">"post"</span>:1,<span class="string">"pageview"</span>:1,<span class="string">"_id"</span>:0&#125;)</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"MongoDB shell"</span>, <span class="string">"pageview"</span> : 3 &#125;</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"start Spring Boot"</span>, <span class="string">"pageview"</span> : 3 &#125;</span><br></pre></td></tr></table></figure><p></p><p><code>$not</code>运算符用于取反，比如取pageview不为3的倍数的博文：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.blog.find(&#123;<span class="string">"pageview"</span>:&#123;<span class="string">"<span class="variable">$not</span>"</span>:&#123;<span class="string">"<span class="variable">$mod</span>"</span>:[3,0]&#125;&#125;&#125;, </span><br><span class="line">...&#123;<span class="string">"post"</span>:1,<span class="string">"pageview"</span>:1,<span class="string">"_id"</span>:0&#125;)</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"MongoDB文档CUD"</span>, <span class="string">"pageview"</span> : 5 &#125;</span><br></pre></td></tr></table></figure><p></p><h3 id="and"><a href="#and" class="headerlink" title="$and"></a>$and</h3><p><code>$and</code>操作符和SQL中的含义类似，比如查找post为MongoDB文档CUD且pageview大于3的文档：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.blog.find(&#123;<span class="string">"<span class="variable">$and</span>"</span>:[&#123;<span class="string">"post"</span>:<span class="string">"MongoDB文档CUD"</span>&#125;,&#123;<span class="string">"pageview"</span>:&#123;<span class="string">"<span class="variable">$gt</span>"</span>:3&#125;&#125;]&#125;,</span><br><span class="line">... &#123;<span class="string">"post"</span>:1,<span class="string">"pageview"</span>:1,<span class="string">"_id"</span>:0&#125;)</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"MongoDB文档CUD"</span>, <span class="string">"pageview"</span> : 5 &#125;</span><br></pre></td></tr></table></figure><p></p><h2 id="特定类型的查询"><a href="#特定类型的查询" class="headerlink" title="特定类型的查询"></a>特定类型的查询</h2><p><code>null</code>。查询文档某个键的值为<code>null</code>，会将不包含该键的文档也查询出来，比如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.blog.find(&#123;&#125;,&#123;<span class="string">"post"</span>:1,<span class="string">"like"</span>:1,<span class="string">"_id"</span>:0&#125;)</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"MongoDB文档CUD"</span>, <span class="string">"like"</span> : 2 &#125;</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"MongoDB shell"</span> &#125;</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"start Spring Boot"</span>, <span class="string">"like"</span> : null &#125;</span><br><span class="line">&gt; db.blog.find(&#123;<span class="string">"like"</span>:null&#125;,&#123;<span class="string">"post"</span>:1,<span class="string">"like"</span>:1,<span class="string">"_id"</span>:0&#125;)</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"MongoDB shell"</span> &#125;</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"start Spring Boot"</span>, <span class="string">"like"</span> : null &#125;</span><br></pre></td></tr></table></figure><p></p><p>可以通过<code>$exists</code>条件判断键是否存在，比如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.blog.find(&#123;<span class="string">"like"</span>:&#123;<span class="string">"<span class="variable">$in</span>"</span>:[null],<span class="string">"<span class="variable">$exists</span>"</span>:<span class="literal">true</span>&#125;&#125;, </span><br><span class="line">...&#123;<span class="string">"post"</span>:1,<span class="string">"like"</span>:1,<span class="string">"_id"</span>:0&#125;)</span><br><span class="line">&#123; <span class="string">"post"</span> : <span class="string">"start Spring Boot"</span>, <span class="string">"like"</span> : null &#125;</span><br></pre></td></tr></table></figure><p></p><p>MongoDB查询也支持键值的正则表达式匹配，这里就懒得记录了。</p><h3 id="查询数组"><a href="#查询数组" class="headerlink" title="查询数组"></a>查询数组</h3><p>先看个栗子：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.food.find()</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45986596dd54570ce1ed"</span>), <span class="string">"fruit"</span> : [ <span class="string">"西瓜"</span>, <span class="string">"香蕉"</span>, <span class="string">"桃子"</span> ] &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45c76596dd54570ce1ee"</span>), <span class="string">"fruit"</span> : [ <span class="string">"西瓜"</span>, <span class="string">"芒果"</span>, <span class="string">"杨桃"</span> ] &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45f76596dd54570ce1ef"</span>), <span class="string">"fruit"</span> : [ <span class="string">"哈密瓜"</span>, <span class="string">"葡萄"</span>, <span class="string">"樱桃"</span> ] &#125;</span><br><span class="line">&gt; db.food.find(&#123;<span class="string">"fruit"</span>:<span class="string">"西瓜"</span>&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45986596dd54570ce1ed"</span>), <span class="string">"fruit"</span> : [ <span class="string">"西瓜"</span>, <span class="string">"香蕉"</span>, <span class="string">"桃子"</span> ] &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45c76596dd54570ce1ee"</span>), <span class="string">"fruit"</span> : [ <span class="string">"西瓜"</span>, <span class="string">"芒果"</span>, <span class="string">"杨桃"</span> ] &#125;</span><br></pre></td></tr></table></figure><p></p><p>查找既包含西瓜又包含芒果的文档，使用<code>$all</code>操作符：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.food.find(&#123;<span class="string">"fruit"</span>:&#123;<span class="string">"<span class="variable">$all</span>"</span>:[<span class="string">"西瓜"</span>,<span class="string">"芒果"</span>]&#125;&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45c76596dd54570ce1ee"</span>), <span class="string">"fruit"</span> : [ <span class="string">"西瓜"</span>, <span class="string">"芒果"</span>, <span class="string">"杨桃"</span> ] &#125;</span><br></pre></td></tr></table></figure><p></p><p>其中，数组中值的顺序不重要。</p><p>如果不使用<code>$all</code> 就是精准匹配了，比如下面这个查询将查询不出任何结果：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.food.find(&#123;<span class="string">"fruit"</span>:[<span class="string">"西瓜"</span>,<span class="string">"芒果"</span>]&#125;)</span><br></pre></td></tr></table></figure><p></p><p>也可以根据数组的下标进行查询，比如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.food.find(&#123;<span class="string">"fruit.1"</span>:<span class="string">"葡萄"</span>&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45f76596dd54570ce1ef"</span>), <span class="string">"fruit"</span> : [ <span class="string">"哈密瓜"</span>, <span class="string">"葡萄"</span>, <span class="string">"樱桃"</span> ] &#125;</span><br></pre></td></tr></table></figure><p></p><p><code>$size</code>操作符用于根据数组的长度进行查询匹配，比如查找fruit数组长度为3的文档：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.food.find(&#123;<span class="string">"fruit"</span>:&#123;<span class="string">"<span class="variable">$size</span>"</span>:3&#125;&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45986596dd54570ce1ed"</span>), <span class="string">"fruit"</span> : [ <span class="string">"西瓜"</span>, <span class="string">"香蕉"</span>, <span class="string">"桃子"</span> ] &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45c76596dd54570ce1ee"</span>), <span class="string">"fruit"</span> : [ <span class="string">"西瓜"</span>, <span class="string">"芒果"</span>, <span class="string">"杨桃"</span> ] &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45f76596dd54570ce1ef"</span>), <span class="string">"fruit"</span> : [ <span class="string">"哈密瓜"</span>, <span class="string">"葡萄"</span>, <span class="string">"樱桃"</span> ] &#125;</span><br></pre></td></tr></table></figure><p></p><p>注意：<code>$size</code>操作符不能<code>$gt</code>等比较操作符一起使用！</p><p><code>$slice</code>操作符可以返回某个键匹配的数组元素的一个子集，比如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.food.find(&#123;&#125;,&#123;<span class="string">"fruit"</span>:&#123;<span class="string">"<span class="variable">$slice</span>"</span>:2&#125;&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45986596dd54570ce1ed"</span>), <span class="string">"fruit"</span> : [ <span class="string">"西瓜"</span>, <span class="string">"香蕉"</span> ] &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45c76596dd54570ce1ee"</span>), <span class="string">"fruit"</span> : [ <span class="string">"西瓜"</span>, <span class="string">"芒果"</span> ] &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45f76596dd54570ce1ef"</span>), <span class="string">"fruit"</span> : [ <span class="string">"哈密瓜"</span>, <span class="string">"葡萄"</span> ] &#125;</span><br></pre></td></tr></table></figure><p></p><p>如果想返回数组的后两个元素，可以这样：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.food.find(&#123;&#125;,&#123;<span class="string">"fruit"</span>:&#123;<span class="string">"<span class="variable">$slice</span>"</span>:-2&#125;&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45986596dd54570ce1ed"</span>), <span class="string">"fruit"</span> : [ <span class="string">"香蕉"</span>, <span class="string">"桃子"</span> ] &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45c76596dd54570ce1ee"</span>), <span class="string">"fruit"</span> : [ <span class="string">"芒果"</span>, <span class="string">"杨桃"</span> ] &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45f76596dd54570ce1ef"</span>), <span class="string">"fruit"</span> : [ <span class="string">"葡萄"</span>, <span class="string">"樱桃"</span> ] &#125;</span><br></pre></td></tr></table></figure><p></p><p><code>$slice</code>也可以指定偏移量，比如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.food.find(&#123;&#125;,&#123;<span class="string">"fruit"</span>:&#123;<span class="string">"<span class="variable">$slice</span>"</span>:[1,3]&#125;&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45986596dd54570ce1ed"</span>), <span class="string">"fruit"</span> : [ <span class="string">"香蕉"</span>, <span class="string">"桃子"</span> ] &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45c76596dd54570ce1ee"</span>), <span class="string">"fruit"</span> : [ <span class="string">"芒果"</span>, <span class="string">"杨桃"</span> ] &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ad45f76596dd54570ce1ef"</span>), <span class="string">"fruit"</span> : [ <span class="string">"葡萄"</span>, <span class="string">"樱桃"</span> ] &#125;</span><br></pre></td></tr></table></figure><p></p><p>[1,1]表示跳过前1个元素，返回第2~3个元素，如果没有那么多元素，就返回第2个元素之后的所有元素。</p><h3 id="数组的范围查询"><a href="#数组的范围查询" class="headerlink" title="数组的范围查询"></a>数组的范围查询</h3><p>数组的范围查询需要注意一个问题，如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.test.find()</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b0eca3a263b332501bc7b5"</span>), <span class="string">"x"</span> : 5 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b0eca9a263b332501bc7b6"</span>), <span class="string">"x"</span> : 15 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b0ecaea263b332501bc7b7"</span>), <span class="string">"x"</span> : 25 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b0ecbda263b332501bc7b8"</span>), <span class="string">"x"</span> : [ 5, 25 ] &#125;    </span><br><span class="line">&gt; db.test.find(&#123;<span class="string">"x"</span>:&#123;<span class="string">"<span class="variable">$gt</span>"</span>:10,<span class="string">"<span class="variable">$lt</span>"</span>:20&#125;&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b0eca9a263b332501bc7b6"</span>), <span class="string">"x"</span> : 15 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b0ecbda263b332501bc7b8"</span>), <span class="string">"x"</span> : [ 5, 25 ] &#125;</span><br></pre></td></tr></table></figure><p></p><p>查询结果不符合预期，因为数组中的5符合<code>$lt:20，25</code>符合<code>$gt:10</code>。要对数组元素进行范围查询，可借助<code>$elemMatch</code>操作符：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.test.find(&#123;<span class="string">"x"</span>:&#123;<span class="string">"<span class="variable">$elemMatch</span>"</span>:&#123;<span class="string">"<span class="variable">$gt</span>"</span>:10,<span class="string">"<span class="variable">$lt</span>"</span>:20&#125;&#125;&#125;)</span><br><span class="line">&gt; //查询不到任何结果</span><br></pre></td></tr></table></figure><p></p><p>这个查询没有任何结果，因为<code>{ &quot;_id&quot; : ObjectId(&quot;58b0eca9a263b332501bc7b6&quot;), &quot;x&quot; : 15 }</code>文档x的值不是数组类型，并且<code>$elemMatch</code>操作符使得数组元素的每一个值都必须与条件相匹配。</p><h3 id="查询内嵌文档"><a href="#查询内嵌文档" class="headerlink" title="查询内嵌文档"></a>查询内嵌文档</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.blog.find().pretty()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"_id"</span> : ObjectId(<span class="string">"58b11d0ca263b332501bc7b9"</span>),</span><br><span class="line">    <span class="string">"title"</span> : <span class="string">"MongoDB查询"</span>,</span><br><span class="line">    <span class="string">"like"</span> : <span class="string">"2"</span>,</span><br><span class="line">    <span class="string">"comments"</span> : &#123;</span><br><span class="line">        <span class="string">"name"</span> : <span class="string">"ltsc"</span>,</span><br><span class="line">        <span class="string">"comment"</span> : <span class="string">"good post"</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"_id"</span> : ObjectId(<span class="string">"58b11daca263b332501bc7ba"</span>),</span><br><span class="line">    <span class="string">"title"</span> : <span class="string">"MongoDB shell"</span>,</span><br><span class="line">    <span class="string">"like"</span> : <span class="string">"3"</span>,</span><br><span class="line">    <span class="string">"comments"</span> : [</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="string">"name"</span> : <span class="string">"ltsc"</span>,</span><br><span class="line">                <span class="string">"comment"</span> : <span class="string">"good post"</span></span><br><span class="line">            &#125;,</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="string">"name"</span> : <span class="string">"xiaohema"</span>,</span><br><span class="line">                <span class="string">"comment"</span> : <span class="string">"不明觉厉"</span></span><br><span class="line">            &#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>要查询包含名为”xiaohema”，并且评论为”不明觉厉的”博文，可以使用以下查询：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.blog.find(&#123;<span class="string">"comments"</span>:&#123;<span class="string">"<span class="variable">$elemMatch</span>"</span>:&#123;<span class="string">"name"</span>:<span class="string">"xiaohema"</span>,<span class="string">"comment"</span>:<span class="string">"不明觉厉"</span>&#125;&#125;&#125;).pretty()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"_id"</span> : ObjectId(<span class="string">"58b11daca263b332501bc7ba"</span>),</span><br><span class="line">    <span class="string">"title"</span> : <span class="string">"MongoDB shell"</span>,</span><br><span class="line">    <span class="string">"like"</span> : <span class="string">"3"</span>,</span><br><span class="line">    <span class="string">"comments"</span> : [</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="string">"name"</span> : <span class="string">"ltsc"</span>,</span><br><span class="line">                <span class="string">"comment"</span> : <span class="string">"good post"</span></span><br><span class="line">            &#125;,</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="string">"name"</span> : <span class="string">"xiaohema"</span>,</span><br><span class="line">                <span class="string">"comment"</span> : <span class="string">"不明觉厉"</span></span><br><span class="line">            &#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><h2 id="where查询"><a href="#where查询" class="headerlink" title="$where查询"></a>$where查询</h2><p>当一般查询都不能满足查询要求的时候，可以考虑使用<code>$where</code>操作符，比如有如下文档：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.food.find(&#123;&#125;,&#123;<span class="string">"_id"</span>:0&#125;)</span><br><span class="line">&#123; <span class="string">"草莓蛋糕"</span> : 4, <span class="string">"芝士蛋糕"</span> : 5, <span class="string">"巧克力蛋糕"</span> : 4 &#125;</span><br><span class="line">&#123; <span class="string">"摩卡咖啡"</span> : 3, <span class="string">"拿铁咖啡"</span> : 6, <span class="string">"热巧克力"</span> : 1 &#125;</span><br></pre></td></tr></table></figure><p></p><p>现要查询含有相同数量食物的文档，可以使用<code>$where</code>操作符：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.food.find(&#123;<span class="string">"<span class="variable">$where</span>"</span>:<span class="function"><span class="title">function</span></span>()&#123;</span><br><span class="line">... <span class="keyword">for</span>(var current <span class="keyword">in</span> this)&#123;</span><br><span class="line">...     <span class="keyword">for</span>(var next <span class="keyword">in</span> this)&#123;</span><br><span class="line">...         <span class="keyword">if</span>(current != next &amp;&amp; this[current] == this[next])&#123;</span><br><span class="line">...             <span class="built_in">return</span> <span class="literal">true</span>;</span><br><span class="line">...         &#125;</span><br><span class="line">...     &#125;</span><br><span class="line">... &#125;</span><br><span class="line">... &#125;&#125;,&#123;<span class="string">"_id"</span>:0&#125;)</span><br><span class="line">&#123; <span class="string">"草莓蛋糕"</span> : 4, <span class="string">"芝士蛋糕"</span> : 5, <span class="string">"巧克力蛋糕"</span> : 4 &#125;</span><br></pre></td></tr></table></figure><p></p><p>但是在实际情况下，出于对性能和安全的考虑，应该尽量不使用<code>$where</code>。</p><h2 id="游标"><a href="#游标" class="headerlink" title="游标"></a>游标</h2><p>MongoDB使用游标返回<code>find</code>查询结果，使用<code>hasNext</code>函数判断游标中是否还有其他结果，使用<code>next</code>函数来迭代结果，如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="keyword">function</span> <span class="function"><span class="title">create</span></span>()&#123;</span><br><span class="line">... db.test.drop();</span><br><span class="line">... <span class="keyword">for</span>(var i = 0;i&lt;100;i++)&#123;</span><br><span class="line">...     db.test.insert(&#123;<span class="string">"x"</span>:i&#125;);</span><br><span class="line">... &#125;&#125;</span><br><span class="line">&gt; create()</span><br><span class="line">&gt; var cursor = db.test.find()</span><br><span class="line">&gt; cursor.hasNext()</span><br><span class="line"><span class="literal">true</span></span><br><span class="line">&gt; cursor.next()</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b12834a263b332501bc7bd"</span>), <span class="string">"x"</span> : 0 &#125;</span><br><span class="line">&gt; cursor.next()</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b12834a263b332501bc7be"</span>), <span class="string">"x"</span> : 1 &#125;</span><br><span class="line">&gt; cursor.next()</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b12834a263b332501bc7bf"</span>), <span class="string">"x"</span> : 2 &#125;</span><br></pre></td></tr></table></figure><p></p><p>游标还实现了JavaScript的迭代器接口，可以使用<code>forEach</code>循环来迭代输出结果：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&gt; cursor.forEach(<span class="keyword">function</span>(x)&#123;</span><br><span class="line">... <span class="built_in">print</span>(x.x);</span><br><span class="line">... &#125;)</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">...</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">&gt; cursor.hasNext()</span><br><span class="line"><span class="literal">false</span></span><br></pre></td></tr></table></figure><p></p><h3 id="limit，skip和sort"><a href="#limit，skip和sort" class="headerlink" title="limit，skip和sort"></a>limit，skip和sort</h3><p><code>limit</code>用于限制返回结果的数量，比如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.test.find().<span class="built_in">limit</span>(3)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b12834a263b332501bc7bd"</span>), <span class="string">"x"</span> : 0 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b12834a263b332501bc7be"</span>), <span class="string">"x"</span> : 1 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b12834a263b332501bc7bf"</span>), <span class="string">"x"</span> : 2 &#125;</span><br></pre></td></tr></table></figure><p></p><p>要是匹配的数量还不到3个，则返回匹配的数量。</p><p><code>skip</code>则是用于跳过N个数量后，返回剩下的查询结果，比如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.test.find().skip(97)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b12834a263b332501bc81e"</span>), <span class="string">"x"</span> : 97 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b12834a263b332501bc81f"</span>), <span class="string">"x"</span> : 98 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b12834a263b332501bc820"</span>), <span class="string">"x"</span> : 99 &#125;</span><br></pre></td></tr></table></figure><p></p><p><code>sort</code>则是用于对返回结果的排序，-1表示降序，1表示升序，如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.test.find().<span class="built_in">limit</span>(4).sort(&#123;<span class="string">"x"</span>:-1&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b12834a263b332501bc820"</span>), <span class="string">"x"</span> : 99 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b12834a263b332501bc81f"</span>), <span class="string">"x"</span> : 98 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b12834a263b332501bc81e"</span>), <span class="string">"x"</span> : 97 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58b12834a263b332501bc81d"</span>), <span class="string">"x"</span> : 96 &#125;</span><br></pre></td></tr></table></figure><p></p><p>当使用<code>skip</code>略过较多数量文档时，速度会变得很慢，比如常用的分页需求：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; var page1 = db.test.find().<span class="built_in">limit</span>(100)</span><br><span class="line">&gt; var page2 = db.test.find().skip(100).<span class="built_in">limit</span>(100)</span><br><span class="line">&gt; var page3 = db.test.find().skip(200).<span class="built_in">limit</span>(100)</span><br></pre></td></tr></table></figure><p></p><p>正如前面所说的，这会导致速度很慢，可以使用下面这种思路取代，比如使用<code>date</code>降序来显示文档列表：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt; var page1 = db.test.find().sort(&#123;<span class="string">"date"</span>:-1&#125;).<span class="built_in">limit</span>(100)</span><br></pre></td></tr></table></figure><p></p><p>然后可以使用最后一个文档的<code>date</code>作为查询条件，如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">var latest = null</span><br><span class="line"><span class="keyword">while</span>(page1.hasNext())&#123;</span><br><span class="line">    latest = page1.next();</span><br><span class="line">&#125;</span><br><span class="line">//获取下一页</span><br><span class="line">var page2 = db.test.find(&#123;<span class="string">"date"</span>:&#123;<span class="string">"<span class="variable">$gt</span>"</span>:&#123;latest.date&#125;&#125;&#125;);</span><br><span class="line">page2.sort(&#123;<span class="string">"date"</span>:-1&#125;).<span class="built_in">limit</span>(100);</span><br></pre></td></tr></table></figure><p></p><h3 id="获取的一致性"><a href="#获取的一致性" class="headerlink" title="获取的一致性"></a>获取的一致性</h3><p>看个栗子：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">var cursor = db.test.find();</span><br><span class="line"><span class="keyword">while</span>(cursor.hasNext())&#123;</span><br><span class="line">    var current = curosr.next();</span><br><span class="line">    var modify = process(current);</span><br><span class="line">    db.test.save(modify);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>其中<code>process</code>为某个修改文档函数。这样做当文档较大的时候，游标可能会多次返回同一个文档，而并不能预期的进行遍历。</p><p>因为当保存文档的时候，如果文档较大，文档间的空隙又不足，这时候文档无法预期的保存回数据库，MongoDB会将其挪至集合的末尾，为了避免这种情况，我们可以对查询添加快照。使用查询快照后，查询会对”_id”进行遍历，这就保证了每个文档只会返回一次，修改上述查询：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var cursor = db.test.find().snapshot();</span><br></pre></td></tr></table></figure><p></p><blockquote><p><a href="https://book.douban.com/subject/25960887/" target="_blank" rel="noopener">《MongoDB权威指南》</a>读书笔记</p></blockquote><script>$(".post-body a").not(".thispage").addClass("ignore-href").attr("target","_blank")</script></div><div></div><div><div style="padding:10px 0;margin:20px auto;width:90%;text-align:center;color:#878787"><div>请作者喝瓶肥宅水~</div><button id="rewardButton" style="margin-top:10px" disable="enable" onclick='var e=document.getElementById("QR");"none"===e.style.display?e.style.display="block":e.style.display="none"'><span style="height:46px;width:46px;line-height:46px;border-radius:50%;color:#fe5f55;font-weight:600;background:#ffd5be;border:none;box-shadow:0 4px 8px 0 rgba(255,213,190,.4)">￥</span></button><div id="QR" style="display:none"><div id="wechat" style="display:inline-block"><img id="wechat_qr" src="/img/wechat_pay.png" alt="MrBird WeChat Pay"></div><div id="alipay" style="display:inline-block"><img id="alipay_qr" src="/img/ali_pay.png" alt="MrBird Alipay"></div></div></div><style>#QR img{width:auto;margin:.8em 1em 0 1em}</style></div><div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者：</strong> MrBird</li><li class="post-copyright-link"><strong>本文链接：</strong> <a href="http://mrbird.cc/MongoDB-文档查询.html" title="MongoDB 文档查询">http://mrbird.cc/MongoDB-文档查询.html</a></li><li class="post-copyright-license"><strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li></ul></div><footer class="post-footer"><div class="post-tags" style="margin-bottom:1.3rem"><a href="/tags/MongoDB/" rel="tag"># MongoDB</a> <a href="/tags/DataBase/" rel="tag"># DataBase</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/MongoDB文档CUD.html" rel="next" title="MongoDB文档CUD"><i class="fa fa-chevron-left"></i> MongoDB文档CUD</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"><a href="/Servlet状态管理.html" rel="prev" title="Servlet状态管理">Servlet状态管理 <i class="fa fa-chevron-right"></i></a></div></div></footer></article><hr><div id="container"></div><div class="post-spread"><div id="comment-div"></div><style>.valine .vlist{margin-bottom:3rem}.valine .vwrap .vcontrol .col.col-60{text-align:left}.valine .vlist .vcard .vhead,.valine .vlist .vcard section .vfooter{text-align:left}.valine .vlist .vcard section{padding-bottom:.5rem!important}.vname{color:#42b983!important}.valine .vinfo .col{text-align:left;margin-left:-27rem}div#comment-div{margin-bottom:-8rem}.valine .vlist .vcard .vcontent .code,.valine .vlist .vcard .vcontent code,.valine .vlist .vcard .vcontent pre{background:#fbfbfb}.valine .vlist .vcard .vcontent a{color:#42b983}.valine .vlist .vcard .vimg{border-radius:3px}.valine .vbtn{border-radius:2px;padding:.3rem 1.25rem}.valine .vbtn:active,.valine .vbtn:hover{color:#42b983;border-color:#42b983;background-color:#fff}.valine .vwrap .vheader .vinput:focus{border-bottom-color:#42b983}.valine .vlist .vcard .vcontent.expand:before{background:-webkit-gradient(linear,left top,left bottom,from(hsla(0,0%,100%,0)),to(hsla(0,0%,100%,.2)));background:linear-gradient(180deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.2))}.valine .vlist .vcard .vcontent.expand:after{content:"点击展开";font-size:.4rem;text-align:right;left:-1rem;background:hsla(0,0%,100%,.2)}.valine .vlist .vcard section .vfooter .vat{color:#b3b3b3}.valine .vlist .vcard section .vfooter .vat:hover{color:#42b983}.vcontent img{margin:0}.valine .info{display:none}</style><script type="text/javascript" src="/js/av.min.js"></script><script type="text/javascript" src="/js/Valine.min.js"></script><script type="text/javascript" src="/js/activate-power-mode.js"></script><script>POWERMODE.colorful=!0,POWERMODE.shake=!1,document.body.addEventListener("input",POWERMODE),new Valine({el:"#comment-div",notify:!1,verify:!0,appId:"SMcDFP1bN1jgb9Lo8JmtICHm-gzGzoHsz",appKey:"dH4nrUrt3V5XiJiI6Qyejnbi",placeholder:"",path:window.location.pathname,avatar:"monsterid",guest_info:["nick","mail","link"]});var chicken='<a href="#"><img src="https://image.uisdc.com/wp-content/uploads/2018/06/uisdc-chat-chicken.gif" class="checken"></a>';$("#comment-div").prepend(chicken)</script></div></div><script>var $bqinline=$("img[alt='bq-inline']");$bqinline.css({width:"2.3rem",height:"2.3rem",display:"inline","vertical-align":"text-bottom"})</script></div><div class="comments" id="comments"></div></div><aside id="sidebar" class="sidebar" onselectstart="return!1"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">Contents</li><li class="sidebar-nav-overview" data-target="site-overview">Site Preview</li></ul><section class="site-overview sidebar-panel"><div class="sidebar-sticky sticky"><div itemscope itemtype="http://schema.org/Person"><div class="author__avatar"><img src="/images/blogImage.jpg" class="author__avatar" alt="MrBird" itemprop="image"></div><div class="author__content"><h3 class="author__name" itemprop="name">MrBird's Blog</h3><p class="author__bio" itemprop="description">A simple blog, code repository, just keep blogging</p></div><div class="author__urls-wrapper"><button class="btn btn--inverse">Follow</button><ul class="author__urls social-icons"><li><a href="http://map.baidu.com/?newmap=1&s=s%26wd%3D%E7%A6%8F%E5%B7%9E%E5%B8%82%26c%3D300&from=alamap&tpl=mapcity" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-map-marker" aria-hidden="true"></i>&nbsp;&nbsp;FuZhou,CN</a></li><li><a href="https://love.mrbird.cc" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-diamond" aria-hidden="true"></i>&nbsp;&nbsp;Love</a></li><li><a href="https://cloud.mrbird.cn" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-chain" aria-hidden="true"></i>&nbsp;&nbsp;FEBS</a></li><li><a href="/atom.xml" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-rss" aria-hidden="true"></i>&nbsp;&nbsp;RSS</a></li><li><a href="https://gitee.com/mrbirdd" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-codepen" aria-hidden="true"></i>&nbsp;&nbsp;Gitee</a></li><li><a href="https://github.com/wuyouzhuguli" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-github-alt" aria-hidden="true"></i>&nbsp;&nbsp;GitHub</a></li><li><a href="javascript:;" class="popup-trigger"><i class="fa fa-fw fa-search" aria-hidden="true"></i>&nbsp;&nbsp;Search</a></li></ul></div></div></div><script>var $urls=$(".author__urls").find("a");$urls.each(function(){var o=$(this);o.mouseenter(function(){o.css({color:"#414547"})}),o.mouseleave(function(){o.css({color:""})})})</script></section><section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#find简介"><span class="nav-number">1.</span> <span class="nav-text">find简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查询条件"><span class="nav-number">2.</span> <span class="nav-text">查询条件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#比较操作符"><span class="nav-number">2.1.</span> <span class="nav-text">比较操作符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#OR查询"><span class="nav-number">2.2.</span> <span class="nav-text">OR查询</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#not"><span class="nav-number">2.3.</span> <span class="nav-text">$not</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#and"><span class="nav-number">2.4.</span> <span class="nav-text">$and</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#特定类型的查询"><span class="nav-number">3.</span> <span class="nav-text">特定类型的查询</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#查询数组"><span class="nav-number">3.1.</span> <span class="nav-text">查询数组</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数组的范围查询"><span class="nav-number">3.2.</span> <span class="nav-text">数组的范围查询</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查询内嵌文档"><span class="nav-number">3.3.</span> <span class="nav-text">查询内嵌文档</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#where查询"><span class="nav-number">4.</span> <span class="nav-text">$where查询</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#游标"><span class="nav-number">5.</span> <span class="nav-text">游标</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#limit，skip和sort"><span class="nav-number">5.1.</span> <span class="nav-text">limit，skip和sort</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#获取的一致性"><span class="nav-number">5.2.</span> <span class="nav-text">获取的一致性</span></a></li></ol></li></ol></div></div></section></div></aside></div></main><footer id="footer" class="footer" onselectstart="return!1"><div class="footer-inner"><div class="copyright">&copy; 2016 - <span itemprop="copyrightYear">2019</span>&nbsp;&nbsp; <span class="author" itemprop="copyrightHolder">MrBird</span>&nbsp;&nbsp;|<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>&nbsp;&nbsp;UV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_uv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span> &nbsp;&nbsp;PV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_pv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span></div></div></footer><div class="back-to-top"><span style="font-family:'Source Sans Pro','Helvetica Neue',Arial,sans-serif;font-size:1.2em;font-weight:600">TOP</span></div></div><script type="text/javascript">"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script><script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script><script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script><script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script><script type="text/javascript">function proceedsearch(){$("body").append('<div class="search-popup-overlay local-search-pop-overlay"></div>').css("overflow","hidden"),$(".search-popup-overlay").click(onPopupClose),$(".popup").toggle();var t=$("#local-search-input");t.attr("autocapitalize","none"),t.attr("autocorrect","off"),t.focus()}var isfetched=!1,isXml=!0,search_path="search.xml";0===search_path.length?search_path="search.xml":search_path.endsWith("json")&&(isXml=!1);var path="/"+search_path,onPopupClose=function(t){$(".popup").hide(),$("#local-search-input").val(""),$(".search-result-list").remove(),$("#no-result").remove(),$(".local-search-pop-overlay").remove(),$("body").css("overflow","")},searchFunc=function(t,e,o){"use strict";$("body").append('<div class="search-popup-overlay local-search-pop-overlay"><div id="search-loading-icon"><i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i></div></div>').css("overflow","hidden"),$("#search-loading-icon").css("margin","20% auto 0 auto").css("text-align","center"),$.ajax({url:t,dataType:isXml?"xml":"json",async:!0,success:function(t){isfetched=!0,$(".popup").detach().appendTo(".header-inner");var n=isXml?$("entry",t).map(function(){return{title:$("title",this).text(),content:$("content",this).text(),url:$("url",this).text()}}).get():t,r=document.getElementById(e),s=document.getElementById(o),a=function(){var t=r.value.trim().toLowerCase(),e=t.split(/[\s\-]+/);e.length>1&&e.push(t);var o=[];if(t.length>0&&n.forEach(function(n){function r(e,o,n,r){for(var s=r[r.length-1],a=s.position,i=s.word,l=[],h=0;a+i.length<=n&&0!=r.length;){i===t&&h++,l.push({position:a,length:i.length});var p=a+i.length;for(r.pop();0!=r.length&&(s=r[r.length-1],a=s.position,i=s.word,p>a);)r.pop()}return c+=h,{hits:l,start:o,end:n,searchTextCount:h}}function s(t,e){var o="",n=e.start;return e.hits.forEach(function(e){o+=t.substring(n,e.position);var r=e.position+e.length;o+='<b class="search-keyword">'+t.substring(e.position,r)+"</b>",n=r}),o+=t.substring(n,e.end)}var a=!1,i=0,c=0,l=n.title.trim(),h=l.toLowerCase(),p=n.content.trim().replace(/<[^>]+>/g,""),u=p.toLowerCase(),f=decodeURIComponent(n.url),d=[],g=[];if(""!=l&&(e.forEach(function(t){function e(t,e,o){var n=t.length;if(0===n)return[];var r=0,s=[],a=[];for(o||(e=e.toLowerCase(),t=t.toLowerCase());(s=e.indexOf(t,r))>-1;)a.push({position:s,word:t}),r=s+n;return a}d=d.concat(e(t,h,!1)),g=g.concat(e(t,u,!1))}),(d.length>0||g.length>0)&&(a=!0,i=d.length+g.length)),a){[d,g].forEach(function(t){t.sort(function(t,e){return e.position!==t.position?e.position-t.position:t.word.length-e.word.length})});var v=[];0!=d.length&&v.push(r(l,0,l.length,d));for(var C=[];0!=g.length;){var $=g[g.length-1],m=$.position,x=$.word,w=m-20,y=m+80;w<0&&(w=0),y<m+x.length&&(y=m+x.length),y>p.length&&(y=p.length),C.push(r(p,w,y,g))}C.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hits.length!==e.hits.length?e.hits.length-t.hits.length:t.start-e.start});var T=parseInt("1");T>=0&&(C=C.slice(0,T));var b="";b+=0!=v.length?"<li><a href='"+f+"' class='search-result-title'>"+s(l,v[0])+"</a>":"<li><a href='"+f+"' class='search-result-title'>"+l+"</a>",C.forEach(function(t){b+="<a href='"+f+'\'><p class="search-result">'+s(p,t)+"...</p></a>"}),b+="</li>",o.push({item:b,searchTextCount:c,hitCount:i,id:o.length})}}),1===e.length&&""===e[0])s.innerHTML='<div id="no-result"><i class="fa fa-search fa-5x" /></div>';else if(0===o.length)s.innerHTML='<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>';else{o.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hitCount!==e.hitCount?e.hitCount-t.hitCount:e.id-t.id});var a='<ul class="search-result-list">';o.forEach(function(t){a+=t.item}),a+="</ul>",s.innerHTML=a}};r.addEventListener("input",a),$(".local-search-pop-overlay").remove(),$("body").css("overflow",""),proceedsearch()}})};$(".popup-trigger").click(function(t){t.stopPropagation(),isfetched===!1?searchFunc(path,"local-search-input","local-search-result"):proceedsearch()}),$(".popup-btn-close").click(onPopupClose),$(".popup").click(function(t){t.stopPropagation()}),$(document).on("keyup",function(t){var e=27===t.which&&$(".search-popup").is(":visible");e&&onPopupClose()})</script></body><script>$(function(){$("a").not(".nav-link,.cloud-tie-join-count,.ignore-href,.jstree-anchor").addClass("animsition-link")});var burst1=new mojs.Burst({left:0,top:0,radius:{5:40},children:{shape:"circle",fill:["red","cyan","orange"],fillOpacity:.8,radiusX:3.5,radiusY:3.5}});document.addEventListener("click",function(a){null==a.target.href&&"footer"!=a.target.className&&"copyright"!=a.target.className&&"author__urls social-icons"!=a.target.className&&"author__avatar"!=a.target.className&&"sidebar sidebar-active"!=a.target.className&&burst1.tune({x:a.pageX,y:a.pageY}).generate().replay()})</script><script type="text/javascript" src="/js/message.js"></script></html><!-- rebuild by neat -->